const { asyncHandler } = require('../../middleware/errorHandler');
const { success, error, paginate, paginateResponse, encryptPassword } = require('../../utils/common');
const { Op } = require('sequelize');
const User = require('../../models/User');
const logger = require('../../utils/logger');

class UserController {
  /**
   * 管理员列表
   */
  static index = asyncHandler(async (req, res) => {
    const { page = 1, limit = 10, username, email, role, status } = req.query;
    
    const where = { role: { [Op.in]: ['admin', 'super_admin'] } };
    if (username) where.username = { [Op.like]: `%${username}%` };
    if (email) where.email = { [Op.like]: `%${email}%` };
    if (role) where.role = role;
    if (status) where.status = status;

    const { offset, limit: pageLimit } = paginate(page, limit);
    
    const { count, rows } = await User.findAndCountAll({
      where,
      attributes: { exclude: ['password'] },
      offset,
      limit: pageLimit,
      order: [['created_at', 'DESC']]
    });

    res.json(paginateResponse(rows, count, page, limit));
  });

  /**
   * 添加管理员页面数据
   */
  static add = asyncHandler(async (req, res) => {
    // 获取角色列表
    const roles = [
      { id: 'admin', name: '管理员' },
      { id: 'super_admin', name: '超级管理员' }
    ];

    res.json(success({ roles }, '获取成功'));
  });

  /**
   * 添加管理员
   */
  static addPost = asyncHandler(async (req, res) => {
    const { username, password, email, nickname, role } = req.body;

    // 验证必填字段
    if (!username || !password || !role) {
      return res.status(400).json(error('用户名、密码和角色为必填项'));
    }

    // 检查用户名是否已存在
    const existingUser = await User.findOne({
      where: {
        [Op.or]: [
          { username },
          ...(email ? [{ email }] : [])
        ]
      }
    });

    if (existingUser) {
      return res.status(400).json(error('用户名或邮箱已存在'));
    }

    // 加密密码
    const hashedPassword = await encryptPassword(password);

    // 创建管理员
    const user = await User.create({
      username,
      password: hashedPassword,
      email,
      nickname: nickname || username,
      role,
      status: 'active'
    });

    logger.info(`超级管理员 ${req.user.id} 创建管理员: ${user.id}`);

    res.json(success(user, '管理员创建成功'));
  });

  /**
   * 编辑管理员页面数据
   */
  static edit = asyncHandler(async (req, res) => {
    const { id } = req.params;

    const user = await User.findByPk(id, {
      attributes: { exclude: ['password'] }
    });

    if (!user) {
      return res.status(404).json(error('用户不存在'));
    }

    // 获取角色列表
    const roles = [
      { id: 'admin', name: '管理员' },
      { id: 'super_admin', name: '超级管理员' }
    ];

    res.json(success({ user, roles }, '获取成功'));
  });

  /**
   * 更新管理员
   */
  static editPost = asyncHandler(async (req, res) => {
    const { id } = req.params;
    const { username, email, nickname, role, status } = req.body;

    const user = await User.findByPk(id);
    if (!user) {
      return res.status(404).json(error('用户不存在'));
    }

          // 检查用户名是否已被其他用户使用
      if (username) {
        const existingUser = await User.findOne({
          where: {
            [Op.and]: [
              {
                [Op.or]: [
                  { username },
                  ...(email ? [{ email }] : [])
                ]
              },
              {
                id: { [Op.ne]: id }
              }
            ]
          }
        });

        if (existingUser) {
          return res.status(400).json(error('用户名或邮箱已被使用'));
        }
      }

    // 更新用户信息
    const updateData = {};
    if (username) updateData.username = username;
    if (email) updateData.email = email;
    if (nickname) updateData.nickname = nickname;
    if (role) updateData.role = role;
    if (status) updateData.status = status;

    await user.update(updateData);

    logger.info(`超级管理员 ${req.user.id} 更新管理员: ${id}`);

    res.json(success(null, '管理员更新成功'));
  });

  /**
   * 删除管理员
   */
  static delete = asyncHandler(async (req, res) => {
    const { id } = req.params;

    const user = await User.findByPk(id);
    if (!user) {
      return res.status(404).json(error('用户不存在'));
    }

    // 不能删除自己
    if (user.id === req.user.id) {
      return res.status(400).json(error('不能删除自己'));
    }

    // 软删除
    await user.update({ status: 'banned' });

    logger.info(`超级管理员 ${req.user.id} 删除管理员: ${id}`);

    res.json(success(null, '管理员删除成功'));
  });

  /**
   * 禁用管理员
   */
  static ban = asyncHandler(async (req, res) => {
    const { id } = req.params;

    const user = await User.findByPk(id);
    if (!user) {
      return res.status(404).json(error('用户不存在'));
    }

    await user.update({ status: 'banned' });

    logger.info(`超级管理员 ${req.user.id} 禁用管理员: ${id}`);

    res.json(success(null, '管理员已禁用'));
  });

  /**
   * 启用管理员
   */
  static cancelBan = asyncHandler(async (req, res) => {
    const { id } = req.params;

    const user = await User.findByPk(id);
    if (!user) {
      return res.status(404).json(error('用户不存在'));
    }

    await user.update({ status: 'active' });

    logger.info(`超级管理员 ${req.user.id} 启用管理员: ${id}`);

    res.json(success(null, '管理员已启用'));
  });

  /**
   * 重置密码
   */
  static resetPassword = asyncHandler(async (req, res) => {
    const { id } = req.params;
    const { new_password } = req.body;

    if (!new_password) {
      return res.status(400).json(error('新密码不能为空'));
    }

    const user = await User.findByPk(id);
    if (!user) {
      return res.status(404).json(error('用户不存在'));
    }

    // 加密新密码
    const hashedPassword = await encryptPassword(new_password);
    await user.update({ password: hashedPassword });

    logger.info(`超级管理员 ${req.user.id} 重置管理员密码: ${id}`);

    res.json(success(null, '密码重置成功'));
  });

  /**
   * 获取管理员统计
   */
  static stats = asyncHandler(async (req, res) => {
    const total = await User.count({ where: { role: { [Op.in]: ['admin', 'super_admin'] } } });
    const active = await User.count({ where: { role: { [Op.in]: ['admin', 'super_admin'] }, status: 'active' } });
    const banned = await User.count({ where: { role: { [Op.in]: ['admin', 'super_admin'] }, status: 'banned' } });

    res.json(success({
      total,
      active,
      banned
    }, '获取成功'));
  });
}

module.exports = UserController; 